<?php
// app/api/service/payment/BalancePayment.php
declare(strict_types=1);

namespace app\api\service\payment;

use app\admin\model\finance\UserMoneyLog;
use app\api\logic\PayLogic;
use app\api\logic\UserDocLogic;
use think\facade\Db;

class BalancePayment extends AbstractPayment
{
    protected $userModel;
    protected $moneyLogModel;

    protected $userDocLogic;
    protected $payLogic;

    public function __construct($orderModel, $userModel)
    {
        $this->orderModel = $orderModel;
        $this->userModel = $userModel;
        $this->moneyLogModel = new UserMoneyLog();
        $this->userDocLogic = new UserDocLogic();
        $this->payLogic = new PayLogic();
    }

    public function pay(array $order)
    {
        Db::startTrans();
        try {
            // 检查余额
            $user = $this->userModel->find($order['user_id']);
            // 确保金额为float类型
            $payPrice = floatval($order['total_amount']);
            $userMoney = floatval($user['money']);
            if ($userMoney < $payPrice) {
                throw new \Exception('余额不足');
            }
            // 扣除余额
            $this->userModel->where('id', $order['user_id'])
                ->update(['money' => Db::raw("money - {$payPrice}")]);

            // 记录余额变动
            $this->moneyLogModel->save([
                'user_id' => $order['user_id'],
                'money' => -$order['total_amount'],
                'before' => $user['money'],
                'after' => $userMoney - $payPrice,
                'memo' => "订单支付：{$order['order_no']}",
                'title' => "订单支付：{$order['order_no']}",
                'create_time' => time(),
            ]);
            // 处理成功后的回掉逻辑
            if (!$this->payLogic->handlePaySuccess($order)) {
                throw new \Exception($this->payLogic->getError());
            }
            Db::commit();
            return ['pay_status' => 'success'];
        } catch (\Exception $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }
}